package cn.lijiajia3515.cairo.auth.modules.department;

import cn.lijiajia3515.cairo.auth.domain.mongo.DepartmentMongo;
import cn.lijiajia3515.cairo.mongo.data.MetaMongo;

import java.util.Optional;

public class DepartmentConverter {

	public static Department convert(DepartmentMongo m, DepartmentExtension extension) {
		final Department.DepartmentBuilder<?, ?> builder = Department.builder().id(m.getId());
		if (extension.fields().contains(DepartmentField.NAME)) builder.name(m.getName());
		Optional.of(extension.fields())
			.filter(x -> x.contains(DepartmentField.NAME))
			.flatMap(x -> Optional.ofNullable(m.getName()))
			.ifPresent(builder::name);

		Optional.of(extension.fields())
			.filter(x -> x.contains(DepartmentField.REMARK))
			.flatMap(x -> Optional.ofNullable(m.getRemark()))
			.ifPresent(builder::remark);


		Optional.of(extension.fields())
			.filter(x -> x.contains(DepartmentField.PARENT))
			.flatMap(x -> Optional.ofNullable(m.getParent()))
			.ifPresent(builder::parent);

		Optional.of(extension.fields())
			.filter(x -> x.contains(DepartmentField.PARENT))
			.flatMap(x -> Optional.ofNullable(m.getAncestors()))
			.ifPresent(builder::ancestors);

		Optional.of(extension.fields())
			.filter(x -> x.contains(DepartmentField.SORT))
			.flatMap(x -> Optional.ofNullable(m.getMeta()).map(MetaMongo::getSort))
			.or(() -> Optional.of(-1L))
			.ifPresent(builder::sort);

		builder.remark(m.getRemark());
		return builder.build();
	}


	public static DepartmentTreeNode treeConvert(DepartmentMongo m) {
		return DepartmentTreeNode.builder()
			.id(m.getId())
			.parent(m.getParent())
			.name(m.getName())
			.sort(m.getMeta().getSort())
			.build();
	}

}
